#!/usr/bin/env python3
"""
createrepo_c MCP Server

面向软件：createrepo_c 和 sqliterepo_c
createrepo_c 是用于创建RPM软件仓库元数据的工具
sqliterepo_c 是用于创建SQLite数据库格式仓库元数据的工具

MCP tools 列表：
1. createrepo_c_help_version - 获取createrepo_c帮助信息和版本
2. createrepo_c_create_repo - 创建基本的软件仓库
3. createrepo_c_with_workers - 使用指定工作线程数创建仓库
4. createrepo_c_with_algorithm - 使用指定校验算法创建仓库
5. createrepo_c_with_pkg_filter - 使用包过滤选项创建或更新仓库
6. sqliterepo_c_help_version - 获取sqliterepo_c帮助信息和版本
7. sqliterepo_c_create_db - 创建或更新SQLite数据库格式的仓库

所有tool返回统一JSON结构：
{
  "success": bool,
  "command": str,
  "exit_code": int,
  "stdout": str,
  "stderr": str
}
"""

from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json
from typing import List, Optional

mcp = FastMCP("createrepo_c MCP Server")

@mcp.tool()
def createrepo_c_help_version() -> dict:
    """
    获取createrepo_c的帮助信息和版本信息
    
    返回:
        dict: 包含命令执行结果的统一JSON结构
    """
    try:
        # 获取帮助信息
        help_result = subprocess.run(["createrepo_c", "-h"], capture_output=True, text=True)
        # 获取版本信息
        version_result = subprocess.run(["createrepo_c", "-V"], capture_output=True, text=True)
        
        combined_stdout = f"Help:\n{help_result.stdout}\n\nVersion:\n{version_result.stdout}"
        combined_stderr = f"Help stderr:\n{help_result.stderr}\n\nVersion stderr:\n{version_result.stderr}"
        
        return {
            "success": help_result.returncode == 0 and version_result.returncode == 0,
            "command": "createrepo_c -h && createrepo_c -V",
            "exit_code": help_result.returncode if help_result.returncode != 0 else version_result.returncode,
            "stdout": combined_stdout,
            "stderr": combined_stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": "createrepo_c -h && createrepo_c -V",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Exception occurred: {str(e)}"
        }

@mcp.tool()
def createrepo_c_create_repo(repo_path: str, verbose: bool = False) -> dict:
    """
    创建基本的软件仓库
    
    参数:
        repo_path: 仓库目录路径
        verbose: 是否显示详细输出
        
    返回:
        dict: 包含命令执行结果的统一JSON结构
    """
    try:
        cmd = ["createrepo_c", repo_path]
        if verbose:
            cmd.append("-v")
            
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd) if 'cmd' in locals() else "createrepo_c",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Exception occurred: {str(e)}"
        }

@mcp.tool()
def createrepo_c_with_workers(repo_path: str, workers: int = 5) -> dict:
    """
    使用指定工作线程数创建仓库
    
    参数:
        repo_path: 仓库目录路径
        workers: 工作线程数量，默认为5
        
    返回:
        dict: 包含命令执行结果的统一JSON结构
    """
    try:
        cmd = ["createrepo_c", "--workers", str(workers), repo_path]
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd) if 'cmd' in locals() else "createrepo_c",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Exception occurred: {str(e)}"
        }

@mcp.tool()
def createrepo_c_with_algorithm(repo_path: str, algorithm: str = "sha256") -> dict:
    """
    使用指定校验算法创建仓库
    
    参数:
        repo_path: 仓库目录路径
        algorithm: 校验算法，如sha256、sha512等
        
    返回:
        dict: 包含命令执行结果的统一JSON结构
    """
    try:
        cmd = ["createrepo_c", "-s", algorithm, repo_path]
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd) if 'cmd' in locals() else "createrepo_c",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Exception occurred: {str(e)}"
        }

@mcp.tool()
def createrepo_c_with_pkg_filter(repo_path: str, 
                               exclude_patterns: Optional[List[str]] = None,
                               include_patterns: Optional[List[str]] = None,
                               pkglist_file: Optional[str] = None,
                               update: bool = False) -> dict:
    """
    使用包过滤选项创建或更新仓库
    
    参数:
        repo_path: 仓库目录路径
        exclude_patterns: 要排除的包模式列表
        include_patterns: 要包含的包模式列表
        pkglist_file: 包列表文件路径
        update: 是否更新现有仓库
        
    返回:
        dict: 包含命令执行结果的统一JSON结构
    """
    try:
        cmd = ["createrepo_c", repo_path]
        
        if exclude_patterns:
            for pattern in exclude_patterns:
                cmd.extend(["-x", pattern])
                
        if include_patterns:
            for pattern in include_patterns:
                cmd.extend(["-n", pattern])
                
        if pkglist_file:
            cmd.extend(["-i", pkglist_file])
            
        if update:
            cmd.append("--update")
            
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd) if 'cmd' in locals() else "createrepo_c",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Exception occurred: {str(e)}"
        }

@mcp.tool()
def sqliterepo_c_help_version() -> dict:
    """
    获取sqliterepo_c的帮助信息和版本信息
    
    返回:
        dict: 包含命令执行结果的统一JSON结构
    """
    try:
        # 获取帮助信息
        help_result = subprocess.run(["sqliterepo_c", "-h"], capture_output=True, text=True)
        # 获取版本信息
        version_result = subprocess.run(["sqliterepo_c", "-V"], capture_output=True, text=True)
        
        combined_stdout = f"Help:\n{help_result.stdout}\n\nVersion:\n{version_result.stdout}"
        combined_stderr = f"Help stderr:\n{help_result.stderr}\n\nVersion stderr:\n{version_result.stderr}"
        
        return {
            "success": help_result.returncode == 0 and version_result.returncode == 0,
            "command": "sqliterepo_c -h && sqliterepo_c -V",
            "exit_code": help_result.returncode if help_result.returncode != 0 else version_result.returncode,
            "stdout": combined_stdout,
            "stderr": combined_stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": "sqliterepo_c -h && sqliterepo_c -V",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Exception occurred: {str(e)}"
        }

@mcp.tool()
def sqliterepo_c_create_db(repo_path: str, 
                          xz_format: bool = False,
                          force: bool = False,
                          keep_old: bool = False,
                          verbose: bool = False,
                          quiet: bool = False) -> dict:
    """
    创建或更新SQLite数据库格式的仓库
    
    参数:
        repo_path: 仓库目录路径
        xz_format: 是否使用xz压缩格式（默认使用bz2）
        force: 是否强制重新创建数据库
        keep_old: 是否保留旧数据库文件
        verbose: 是否显示详细输出
        quiet: 是否静默模式
        
    返回:
        dict: 包含命令执行结果的统一JSON结构
    """
    try:
        cmd = ["sqliterepo_c", repo_path]
        
        if xz_format:
            cmd.append("--xz")
        if force:
            cmd.append("--force")
        if keep_old:
            cmd.append("--keep-old")
        if verbose:
            cmd.append("-v")
        if quiet:
            cmd.append("-q")
            
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd) if 'cmd' in locals() else "sqliterepo_c",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Exception occurred: {str(e)}"
        }

if __name__ == "__main__":
    mcp.run()